package com.ll.gulimall.cart.interceptor;

import com.ll.common.constant.AuthConstant;
import com.ll.common.constant.AuthServerConstant;
import com.ll.common.vo.MemberEntityVo;
import com.ll.gulimall.cart.constant.CartConstant;
import com.ll.gulimall.cart.to.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author 21243
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> toThreadLocal = new ThreadLocal<>();

    /**
     * 目标请求之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        UserInfoTo userInfoTo = new UserInfoTo();
        MemberEntityVo member = (MemberEntityVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (member != null) {
            //用户已登录
            userInfoTo.setUserId(member.getId().toString());
        }
        //用户未登录 查看是否有临时用户
        Cookie[] cookies = request.getCookies();
        if (cookies!=null) {
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                if (cookieName.equalsIgnoreCase(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    userInfoTo.setUser_key(cookie.getValue());
                    userInfoTo.setTemp(true);
                }
            }
        }
        //没有临时用户 则生成临时用户
        if (StringUtils.isEmpty(userInfoTo.getUser_key())) {
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUser_key(uuid);
        }

        toThreadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 目标请求之后
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = toThreadLocal.get();
        if(!userInfoTo.getTemp()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUser_key());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIEMOUT);
            response.addCookie(cookie);
        }
    }
}
